package com.wenge.datagroup.storage.dataprocess;

import com.alibaba.fastjson.JSON;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @Author：WeiPengCheng
 * @Date：2022-07-27 10:55
 * @desc:多语言语种分析
 **/
public class MultilingualLanguage {
    private static Logger logger = LoggerFactory.getLogger(MultilingualLanguage.class);
    public String languageUrl;

    public MultilingualLanguage(String languageUrl) {
        this.languageUrl = languageUrl;
    }

    public String analysis(String par, String id) {
        long start = System.currentTimeMillis();
        OkHttpClient httpClient = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        MultipartBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("id", id)
                .addFormDataPart("content", par)
                .build();
        Request request = new Request.Builder()
                .url(languageUrl)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();

        // 4 发起请求获取响应值
        try {
            Response response = httpClient.newCall(request).execute();
            if (response.code() == 200) {
                logger.info("语种分析请求成功!!");
                String data = response.body().string();
                logger.info("语种分析结果:" + JSON.parseObject(data).toJSONString());
                if (JSON.parseObject(data).getString("code").equals("200")) {
                    String string = JSON.parseObject(data).getJSONObject("data").getString("lang");
                    String s = "en";
                    if (string != null) {
                        s = string.split("_")[0];
                    }
                    logger.info("语种分析结果:" + s);
                    return s;
                } else {
                    logger.info("多语言语种分析接口请求异常! code:{}", response.code());
                }

            } else {
                logger.info("多语言语种分析接口请求异常! code:{}", response.code());
            }
        } catch (IOException e) {
            logger.error("多语言语种分析接口请求异常!");
            e.printStackTrace();
        } finally {
            logger.info("多语言语种分析接口处理耗时： " + (System.currentTimeMillis() - start) + " ms");
        }

        return "en";
    }

}
